//
//  Asyn.m
//  成亲坊项目
//
//  Created by dlios on 15-8-24.
//  Copyright (c) 2015年 dlios. All rights reserved.
//



#import "Asyn.h"
#import "Intente.h"
#import "Tools.h"
#import "URL.h"

@interface Asyn ()<NSURLConnectionDataDelegate,NSURLConnectionDelegate>

@end

@implementation Asyn


- (void)dealloc
{
    [super dealloc];
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.receveData = [NSMutableData data];
    }
    return self;
}





+(instancetype)startParser:(NSString *)str partemer:(NSDictionary *)dic file:(NSString *)file block:(void(^)(NSData *data))block  
{
    
    
    NSString *par = @"";
    for (NSString *key in dic) {
        
        if (par.length == 0) {
            par = [NSString stringWithFormat:@"?%@=%@",key,[dic objectForKey:key]];
        }else
        {
            par = [NSString stringWithFormat:@"%@&%@=%@",par,key,[dic objectForKey:key]];
        }
        
    }
    NSString *url = [NSString stringWithFormat:@"%@%@",str,par];
    Asyn *asy = [[Asyn alloc]init];
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
   asy.finished = block;
    
    NSString *netWork = [Intente reachIntenete];
    
    if ([netWork isEqualToString:@"WiFi"]) {
          [asy startParser:url];
        NSLog(@"有网11111111111111");
    }else if ([netWork isEqualToString:@"WWAN"])
    {
        [asy startParser:url];
    }
    else if ([netWork isEqualToString:@"NO"])
    {
        BOOL  judge =[Tools toolsOfHasLibraryPathName:file];
        if (judge) {
            
            //文件路径
            NSString *path = [Tools toolsOfPathFile:file];
            NSLog(@"没网 有本地");
            NSData *data = [ NSData  dataWithContentsOfFile:path];
            
            block(data);
            
        }else
        {
            NSLog(@"没网没本地存储");
        }
        
        
    }
    
    return [asy autorelease];
}

-(void)startParser:(NSString *)str
{
    NSURL *url = [NSURL URLWithString:str];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    [request setHTTPMethod:@"GET"];
    
    [NSURLConnection connectionWithRequest:request delegate:self];
}

//-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
//{
//    
//    NSHTTPURLResponse *current = (NSHTTPURLResponse *)response;
//    NSDictionary *dic = current.allHeaderFields;
////    NSLog(@"%@",dic);
//    
//}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.receveData appendData:data];
    
    
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    
    self.finished(self.receveData);
//    [self.delegate sendeMessage:self.receveData];
    
}






















@end
